package edu.university.demo.core.exception;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.SimpleMappingExceptionResolver;

import edu.university.demo.common.AjaxResult;
import edu.university.demo.common.JsonUtils;

public class GlobalExceptionResolver extends SimpleMappingExceptionResolver {

	@Override
	protected ModelAndView doResolveException(HttpServletRequest request,
			HttpServletResponse response, Object handler, Exception ex) {
		
		String header = request.getHeader("X-Requested-With");
		boolean isAjax = "XMLHttpRequest".equalsIgnoreCase(header);
		if(!isAjax) {
			return super.doResolveException(request, response, handler, ex);
		}else {
			AjaxResult ajaxResult = new AjaxResult();
			ajaxResult.addError(ex.getMessage());
			try {
				String json = JsonUtils.objectToJson(ajaxResult);
				response.setContentType("application/json; charset=utf-8");
				response.getWriter().write(json);
				response.getWriter().flush();
				response.getWriter().close();
				//response.setContentType("application/json; charset=utf-8");
				//response.getOutputStream().write(json.getBytes("UTF-8"));
				
			} catch (IOException e) {
				e.printStackTrace();
			}
			return null;
		}
	}
}
